﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web.Mvc;
using DataAccess.DB;
using DuocThaiBinh.Common;
using DuocThaiBinh.HtmlHelpers;
using DuocThaiBinh.HtmlHelpers.ExportToExcel;
using Newtonsoft.Json;
using WebMatrix.WebData;

namespace DuocThaiBinh.Controllers
{
    public class NhapKhoController : BaseController
    {
        private db_YTeTBEntities db = new db_YTeTBEntities();

        //
        // GET: /NhapKho/
        [Authorize(Roles = "Administrator,Staff")]
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        [Authorize(Roles = "Administrator,Staff")]
        public JsonResult Index(int page, int rows, string sidx, string sord, string from, string to, string filters, bool _search, string masp)
        {
            int currentCuaHangID = Convert.ToInt32(Session["CuaHangID"]);
            var dvccs = db.DVCCs.Where(k => k.CuaHangID == currentCuaHangID);
            List<NhapKho> _nhapkhos = new List<NhapKho>();
            foreach(var dvcc in dvccs)
            {
                var temp = db.NhapKhoes.OrderByDescending(p => p.MaHoaDon).Where(p => p.DVCC.MaDVCC == dvcc.MaDVCC);
                
                if (!string.IsNullOrEmpty(from))
                {
                    temp = temp.Where(p => p.NgayNhapKho >= Util.ConvertObjectToDateTime(from));
                }

                if (!string.IsNullOrEmpty(to))
                {
                    temp = temp.Where(p => p.NgayNhapKho <= Util.ConvertObjectToDateTime(to));
                }
                
                if (!string.IsNullOrEmpty(masp))
                {
                    temp = temp.Where(p => p.Ma_SP != null && p.Ma_SP.ToLower().Contains(masp.ToLower()));
                }

                if (temp != null && temp.Count() > 0)
                {
                    _nhapkhos.AddRange(temp.ToList());
                }
            }

            var nhapkhos = _nhapkhos as IEnumerable<NhapKho>;

            if (_search)
            {
                FiltersJq f = (!_search || string.IsNullOrEmpty(filters)) ? null : JsonConvert.DeserializeObject<FiltersJq>(filters);
                for (int i = 0; i < f.rules.Count; i++)
                {
                    string field = f.rules[i].field;
                    string data = f.rules[i].data;
                    switch (field)
                    {
                        case "MaHoaDon": nhapkhos = nhapkhos.Where(p => p.MaHoaDon.ToLower().Contains(data.ToLower())); break;
                        case "MaDVCC": nhapkhos = nhapkhos.Where(p => p.DVCC.MaDVCC.ToLower().Contains(data.ToLower())); break;
                        case "TenDVCC": nhapkhos = nhapkhos.Where(p => p.DVCC.TenDVCC.ToLower().Contains(data.ToLower())); break;
                        case "DiaChi": nhapkhos = nhapkhos.Where(p => p.DVCC.DiaChi.ToLower().Contains(data.ToLower())); break;

                        default: nhapkhos.Where(p => p.MaHoaDon.ToLower().Contains(data.ToLower())); break;
                    }
                }

            }

            var count = nhapkhos.Count<NhapKho>();
            int total;
            if (count == 0)
                total = 0;
            else
                total = (int)Math.Ceiling((decimal)count / rows);

            var pagedResult = nhapkhos.Skip(rows * (page - 1)).Take(rows).ToList();


            return Json(new
            {
                page = page,
                total = total,
                records = count,
                rows = pagedResult.Select(x => new { x.ID, x.MaHoaDon, x.DVCC.MaDVCC, x.DVCC.TenDVCC, x.DVCC.DiaChi, x.NgayNhapKho, x.TongThanhToan })
            }, JsonRequestBehavior.AllowGet);
        }

        [Authorize(Roles = "Administrator,Staff")]
        public ExcelResult Export(string sidx, string sord, string from, string to, string masp, string filter, bool search)
        {
            int currentCuaHangID = Convert.ToInt32(Session["CuaHangID"]);
            var dvccs = db.DVCCs.Where(k => k.CuaHangID == currentCuaHangID);
            List<NhapKho> _nhapkhos = new List<NhapKho>();
            foreach (var dvcc in dvccs)
            {
                var temp = db.NhapKhoes.OrderByDescending(p => p.MaHoaDon).Where(p => p.DVCC.MaDVCC == dvcc.MaDVCC);

                if (!string.IsNullOrEmpty(from))
                {
                    temp = temp.Where(p => p.NgayNhapKho >= Util.ConvertObjectToDateTime(from));
                }

                if (!string.IsNullOrEmpty(to))
                {
                    temp = temp.Where(p => p.NgayNhapKho <= Util.ConvertObjectToDateTime(to));
                }
                if (!string.IsNullOrEmpty(masp))
                {
                    temp = temp.Where(p => p.Ma_SP != null && p.Ma_SP.ToLower().Contains(masp.ToLower()));
                }

                if (temp != null)
                {
                    _nhapkhos.AddRange(temp.ToList());
                }
            }

            var nhapkhos = _nhapkhos as IEnumerable<NhapKho>;

            if (search)
            {
                FiltersJq f = (!search || string.IsNullOrEmpty(filter)) ? null : JsonConvert.DeserializeObject<FiltersJq>(filter);
                for (int i = 0; i < f.rules.Count; i++)
                {
                    string field = f.rules[i].field;
                    string data = f.rules[i].data;
                    switch (field)
                    {
                        case "MaHoaDon": nhapkhos = nhapkhos.Where(p => p.MaHoaDon.ToLower().Contains(data.ToLower())); break;
                        case "TenDVCC": nhapkhos = nhapkhos.Where(p => p.DVCC.TenDVCC.ToLower().Contains(data.ToLower())); break;
                        case "MaDVCC": nhapkhos = nhapkhos.Where(p => p.DVCC.MaDVCC.ToLower().Contains(data.ToLower())); break;
                        case "DiaChi": nhapkhos = nhapkhos.Where(p => p.DVCC.DiaChi.ToLower().Contains(data.ToLower())); break;
                        default: nhapkhos.Where(p => p.MaHoaDon.ToLower().Contains(data.ToLower())); break;
                    }
                }

            }

            decimal tongthanhtoan = 0;
            DataTable tablenew = new DataTable("Xuatkho");
            tablenew.Columns.Add("Mã hóa đơn");
            tablenew.Columns.Add("DVCC");
            tablenew.Columns.Add("Ngày nhập kho");
            tablenew.Columns.Add("Tổng thanh toán");

            foreach (NhapKho nhapkho in nhapkhos)
            {
                DataRow newrow = tablenew.NewRow();
                newrow["Mã hóa đơn"] = nhapkho.MaHoaDon;
                newrow["DVCC"] = nhapkho.DVCC.TenDVCC;
                DateTime dt = Convert.ToDateTime(nhapkho.NgayNhapKho);
                newrow["Ngày nhập kho"] = dt.ToString("dd/MM/yyyy");
                var tongtt = nhapkho.TongThanhToan;
                newrow["Tổng thanh toán"] = tongtt;
                tongthanhtoan += Util.ConvertCurrencyToMoney(tongtt);
                tablenew.Rows.Add(newrow);
            }
            DataRow newrow1 = tablenew.NewRow();
            newrow1["Ngày nhập kho"] = "Tổng :";
            newrow1["Tổng thanh toán"] = Util.ConvertDecimaToCurrency(tongthanhtoan);
            tablenew.Rows.Add(newrow1);
            string excelFilename = "Thống kê nhập kho " + DateTime.Now.ToString("dd/MM/yyyy") + ".xlsx";

            string[] cellStyle = new[] { "Text", "Text","Text", "Double" };
            var stream = CreateExcelFile.CreateExcelDocument(tablenew, excelFilename);

            return new ExcelResult()
            {
                FileName = excelFilename,
                Stream = stream
            };

        }

        public ActionResult CheckUserExist(string MaHoaDon, string ID)
        {
            NhapKho existMaHoaDon = db.NhapKhoes.Where(p => p.MaHoaDon.Equals(MaHoaDon)).FirstOrDefault();

            if (ID.Equals("undefined"))// mode new
            {
                if (existMaHoaDon != null)
                {
                    return Json(false, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }

            else
            {
                if (existMaHoaDon != null)
                {

                    if (existMaHoaDon.ID != Convert.ToInt32(ID))
                    {
                        return Json(false, JsonRequestBehavior.AllowGet);
                    }
                    else
                    {
                        return Json(true, JsonRequestBehavior.AllowGet);
                    }
                }
                else
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
        }

        public ActionResult IndexThongKe()
        {
            int currentCuaHangID = Convert.ToInt32(Session["CuaHangID"]);
            var dvccs = db.DVCCs.Where(k => k.CuaHangID == currentCuaHangID);
            List<NhapKho> nhapkhoes = new List<NhapKho>();
            foreach (var dvcc in dvccs)
            {
                var temp = db.NhapKhoes.Include(n => n.DVCC).Include(n => n.UserProfile).OrderByDescending(p => p.ID).Where(p => p.ID_DVCC == currentCuaHangID).ToList();
                string txtSearchDVCC = Request.QueryString["dvcc"];
                string dtFrom = Request.QueryString["from"];
                string dtTo = Request.QueryString["to"];
                if (!string.IsNullOrEmpty(txtSearchDVCC))
                {
                    temp = temp.Where(p => p.DVCC.MaDVCC.ToLower().Contains(txtSearchDVCC.ToLower())).ToList();
                }

                if (!string.IsNullOrEmpty(dtFrom))
                {
                    temp = temp.Where(p => p.NgayNhapKho >= Util.ConvertObjectToDateTime(dtFrom)).ToList();
                }
                if (!string.IsNullOrEmpty(dtTo))
                {
                    temp = temp.Where(p => p.NgayNhapKho <= Util.ConvertObjectToDateTime(dtTo)).ToList();
                }

                if (temp != null)
                {
                    nhapkhoes.AddRange(temp.ToList());
                }
            }

            decimal total = 0;
            foreach (NhapKho nk in nhapkhoes)
            {
                if (nk.TongThanhToan != null)
                {
                    decimal tongtt = Util.ConvertCurrencyToMoney(nk.TongThanhToan);
                    total += tongtt;
                }
            }
            ViewBag.TongNhapKho = total;
            return View(nhapkhoes);
        }

        public SanPham GetSPByMaSP(string masp)
        {
            var sp = db.SanPhams.Where(p => p.MaSP == masp).FirstOrDefault();
            return sp;
        }

        public ActionResult Details(int id = 0)
        {
            NhapKho nhapkho = db.NhapKhoes.Find(id);
            if (nhapkho == null || nhapkho.DVCC.CuaHangID != Convert.ToInt32(Session["CuaHangID"]))
            {
                return HttpNotFound();
            }
            var masp = nhapkho.Ma_SP;
            var soluong = nhapkho.SoLuong;
            var gia = nhapkho.Gia;
            var donvi = nhapkho.DonVi;
            List<string> listHSD = new List<string>();
            List<string> listKho = new List<string>();

            var listMaSanPhams = masp.Split(new string[] { ";#" }, StringSplitOptions.None);
            ViewBag.listmasp = listMaSanPhams;
            ViewBag.listsoLuong = soluong.Split(new string[] { ";#" }, StringSplitOptions.None);
            ViewBag.listgia = gia.Split(new string[] { ";#" }, StringSplitOptions.None);
            ViewBag.listDonvi = donvi.Split(new string[] { ";#" }, StringSplitOptions.None);

            foreach (string maSanPham in listMaSanPhams)
            {
                SanPham sp = GetSPByMaSP(maSanPham);
                if (sp != null)
                {
                    var hansudung = sp.HSD;
                    if (hansudung == null)
                    {
                        listHSD.Add(string.Empty);
                    }
                    else
                    {
                        listHSD.Add(Util.ConvertObjectToStringDateTime(sp.HSD));
                    }
                    ///ChinhNH
                    //listKho.Add(sp.Kho.MaKho);
                }
                else
                {
                    listHSD.Add(string.Empty);
                    listKho.Add(string.Empty);
                }
            }
            ViewBag.listHSD = listHSD.ToArray();
            ViewBag.listMaKho = listKho.ToArray();

            return View(nhapkho);
        }

        //
        // GET: /NhapKho/Create
        [Authorize(Roles = "Administrator,Staff")]
        public ActionResult Create()
        {
            var currentUser = db.UserProfiles.Where(u => u.UserName == User.Identity.Name).FirstOrDefault();
            if(currentUser == null) return RedirectToAction("Index", "Home");
            NhapKho nhapkho = db.NhapKhoes.Where(p => p.ID != null).OrderByDescending(p => p.MaHoaDon).FirstOrDefault();
            string mahd = string.Empty;
            if (nhapkho != null)
            {
                var MaNKLast = nhapkho.MaHoaDon.Split(new string[] { "-" }, StringSplitOptions.None);
                if (Convert.ToInt32(MaNKLast[MaNKLast.Length - 2]) == DateTime.Now.Month)
                {
                    var intMaSPnew = Convert.ToInt32(MaNKLast[MaNKLast.Length - 1]) + 1;
                    mahd = "N-" + DateTime.Now.Year + "-" + string.Format("{0:00}", DateTime.Now.Month) + "-" + string.Format("{0:00000}", intMaSPnew);
                }
                else
                {
                    mahd = "N-" + DateTime.Now.Year + "-" + string.Format("{0:00}", DateTime.Now.Month) + "-" + "00001";
                }
            }
            else
            {
                mahd = "N-" + DateTime.Now.Year + "-" + string.Format("{0:00}", DateTime.Now.Month) + "-" + "00001";
            }
            ViewBag.MaHD = mahd;
            ViewBag.ID_DVCC = new SelectList(db.DVCCs.OrderBy(p => p.TenDVCC), "ID", "TenDVCC");
            List<Kho> khoes = new List<Kho>();
            foreach(var userInCuaHang in currentUser.UserInCuaHangs)
            {
                khoes.AddRange(userInCuaHang.CuaHang.Khoes);
            }
            ViewBag.KhoID = new SelectList(khoes.OrderBy(p => p.TenKho), "ID", "TenKho");
            ViewBag.CurrentUserDisplayName = currentUser.DisplayName;
            ViewBag.CurrentUserID = currentUser.UserId;
            return View();
        }

        //
        // POST: /NhapKho/Create
        [Authorize(Roles = "Administrator,Staff")]
        [HttpPost]
        public ActionResult Create(NhapKho nhapkho, FormCollection form)
        {
            var currentUser = db.UserProfiles.Where(u => u.UserName == User.Identity.Name).FirstOrDefault();
            if (currentUser == null) return RedirectToAction("Index", "Home");
            string masp = string.Empty;
            string soluong = string.Empty;
            string gia = string.Empty;
            string donvi = string.Empty;

            List<string> listmasp = new List<string>();
            List<int> listsoluong = new List<int>();
            List<string> listgia = new List<string>();
            string khoID = string.Empty;

            if (ModelState.IsValid)
            {
                foreach (string key in form.AllKeys)
                {
                    if (key.Contains("ma_sp"))
                    {
                        masp += form[key] + ";#";
                        listmasp.Add(form[key]);
                    }
                    if (key.Contains("SoLuong_"))
                    {
                        soluong += form[key] + ";#";
                        var valueSL = form[key];
                        int intValueSL = 0;
                        if (int.TryParse(valueSL, out intValueSL))
                        {
                            listsoluong.Add(intValueSL);
                        }
                    }
                    if (key.Contains("Gia_"))
                    {
                        gia += form[key] + ";#";
                        listgia.Add(gia);
                    }
                    if (key.Contains("DonVi"))
                    {
                        donvi += form[key] + ";#";
                    }
                }
                // update so luong san pham
                for (int i = 0; i < listmasp.Count; i++)
                {
                    string ma_sp_select = listmasp[i];
                    SanPham sp = db.SanPhams.Where(p => p.MaSP == ma_sp_select).FirstOrDefault();
                    SanPhamInKho sanPhamInKho = db.SanPhamInKhoes.Where(s => s.SanPhamID == sp.ID && s.KhoID == nhapkho.KhoID).FirstOrDefault();
                    if (sanPhamInKho == null)
                    {
                        sanPhamInKho = new SanPhamInKho();
                        sanPhamInKho.KhoID = Convert.ToInt32(nhapkho.KhoID);
                        sanPhamInKho.SanPhamID = sp.ID;
                        sanPhamInKho.SoLuong = listsoluong[i];
                        db.SanPhamInKhoes.Add(sanPhamInKho);
                        db.SaveChanges();
                    }
                    else
                    {
                        sanPhamInKho.SoLuong += listsoluong[i];
                        db.Entry(sanPhamInKho).State = EntityState.Modified;
                        db.SaveChanges();
                    }
                }

                nhapkho.Ma_SP = masp;
                nhapkho.SoLuong = soluong;
                nhapkho.Gia = gia;
                nhapkho.DonVi = donvi;

                //update tổng nợ đơn vị cung cấp
                int idDvcc = Convert.ToInt32(nhapkho.ID_DVCC);
                DVCC dvcc = db.DVCCs.Find(idDvcc);
                var tongno = Util.ConvertCurrencyToMoney(dvcc.TongNo) + Util.ConvertCurrencyToMoney(nhapkho.TongThanhToan);
                dvcc.TongNo = Util.ConvertDecimaToCurrency(tongno);
                db.Entry(dvcc).State = EntityState.Modified;

                //Tao moi nhap kho
                db.NhapKhoes.Add(nhapkho);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            ViewBag.ID_DVCC = new SelectList(db.DVCCs, "ID", "TenDVCC", nhapkho.ID_DVCC);
            List<Kho> khoes = new List<Kho>();
            foreach (var userInCuaHang in currentUser.UserInCuaHangs)
            {
                khoes.AddRange(userInCuaHang.CuaHang.Khoes);
            }
            ViewBag.KhoID = new SelectList(khoes.OrderBy(p => p.TenKho), "ID", "TenKho");
            ViewBag.CurrentUserDisplayName = currentUser.DisplayName;
            ViewBag.CurrentUserID = currentUser.UserId;
            return View(nhapkho);
        }

        //
        // GET: /NhapKho/Edit/5
        [Authorize(Roles = "Administrator,Staff")]
        public ActionResult Edit(int id = 0)
        {
            var currentUser = db.UserProfiles.Where(u => u.UserName == User.Identity.Name).FirstOrDefault();
            if (currentUser == null) return RedirectToAction("Index", "Home");
            NhapKho nhapkho = db.NhapKhoes.Find(id);
            if (nhapkho == null || nhapkho.DVCC.CuaHangID != Convert.ToInt32(Session["CuaHangID"]))
            {
                return HttpNotFound();
            }
            
            var masp = nhapkho.Ma_SP;
            var soluong = nhapkho.SoLuong;
            var gia = nhapkho.Gia;
            var donvi = nhapkho.DonVi;
            var listmasanpham = masp.Split(new string[] { ";#" }, StringSplitOptions.None);
            ViewBag.listmasp = listmasanpham;
            ViewBag.listsoLuong = soluong.Split(new string[] { ";#" }, StringSplitOptions.None);
            ViewBag.listgia = gia.Split(new string[] { ";#" }, StringSplitOptions.None);
            ViewBag.listDonvi = donvi.Split(new string[] { ";#" }, StringSplitOptions.None);
            ViewBag.stt = listmasanpham.Length;

            @ViewBag.makhachhang = nhapkho.DVCC.MaDVCC;
            @ViewBag.tenkhachhang = nhapkho.DVCC.TenDVCC;
            @ViewBag.diachikhachhang = nhapkho.DVCC.DiaChi;
            ViewBag.ID_DVCC = new SelectList(db.DVCCs.OrderBy(d => d.TenDVCC), "ID", "TenDVCC", nhapkho.ID_DVCC);
            ViewBag.TenKho = nhapkho.Kho.TenKho;
            ViewBag.CurrentUserDisplayName = currentUser.DisplayName;
            ViewBag.CurrentUserID = currentUser.UserId;
            return View(nhapkho);
        }

        //
        // POST: /NhapKho/Edit/5
        [Authorize(Roles = "Administrator,Staff")]
        [HttpPost]
        public ActionResult Edit(NhapKho nhapkho, FormCollection form)
        {
            var currentUser = db.UserProfiles.Where(u => u.UserName == User.Identity.Name).FirstOrDefault();
            if (currentUser == null) return RedirectToAction("Index", "Home");
            //remove old infomation
            var oldNK = db.NhapKhoes.Find(nhapkho.ID);
            if (oldNK.DVCC.CuaHangID != Convert.ToInt32(Session["CuaHangID"]))
            {
                return RedirectToAction("Index", "Home");
            }
            var old_Masp = oldNK.Ma_SP;
            var old_SoLuong = oldNK.SoLuong;
            var idold_dvcc = oldNK.ID_DVCC;

            if (ModelState.IsValid)
            {
                if (!string.IsNullOrEmpty(old_Masp))
                {
                    var list_old_Masp = old_Masp.Split(new string[] { ";#" }, StringSplitOptions.None);
                    var list_old_SoLuong = old_SoLuong.Split(new string[] { ";#" }, StringSplitOptions.None);
                    for (int i = 0; i < list_old_Masp.Length; i++)
                    {

                        string sp_old_sp = list_old_Masp[i];
                        if (!string.IsNullOrEmpty(sp_old_sp))
                        {
                            SanPham sp = db.SanPhams.Where(p => p.MaSP == sp_old_sp).FirstOrDefault();
                            SanPhamInKho sanPhamInKho = db.SanPhamInKhoes.Where(s => s.SanPhamID == sp.ID && s.KhoID == nhapkho.KhoID).FirstOrDefault();
                            if (sanPhamInKho != null)
                            {
                                sanPhamInKho.SoLuong -= Convert.ToInt32(list_old_SoLuong[i]);
                                db.Entry(sanPhamInKho).State = EntityState.Modified;
                                db.SaveChanges();
                            }
                        }
                    }
                }
                string masp = string.Empty;
                string soluong = string.Empty;
                string gia = string.Empty;
                string donvi = string.Empty;
                List<string> listmasp = new List<string>();
                List<int> listsoluong = new List<int>();
                List<string> listgia = new List<string>();
                foreach (string key in form.AllKeys)
                {
                    if (key.Contains("ma_sp"))
                    {
                        masp += form[key] + ";#";
                        listmasp.Add(form[key]);
                    }
                    if (key.Contains("SoLuong_"))
                    {
                        soluong += form[key] + ";#";
                        listsoluong.Add(Convert.ToInt32(form[key]));
                    }
                    if (key.Contains("Gia_"))
                    {
                        gia += form[key] + ";#";
                        listgia.Add(gia);
                    }
                    if (key.Contains("DonVi"))
                    {
                        donvi += form[key] + ";#";
                    }
                }
                //update so luong
                for (int i = 0; i < listmasp.Count; i++)
                {
                    string ma_sp_select = listmasp[i];
                    SanPham sp = db.SanPhams.Where(p => p.MaSP == ma_sp_select).FirstOrDefault();
                    SanPhamInKho sanPhamInKho = db.SanPhamInKhoes.Where(s => s.SanPhamID == sp.ID && s.KhoID == nhapkho.KhoID).FirstOrDefault();
                    if (sanPhamInKho == null)
                    {
                        sanPhamInKho = new SanPhamInKho();
                        sanPhamInKho.KhoID = Convert.ToInt32(nhapkho.KhoID);
                        sanPhamInKho.SanPhamID = sp.ID;
                        sanPhamInKho.SoLuong = listsoluong[i];
                        db.SanPhamInKhoes.Add(sanPhamInKho);
                        db.SaveChanges();
                    }
                    else
                    {
                        sanPhamInKho.SoLuong += listsoluong[i];
                        db.Entry(sanPhamInKho).State = EntityState.Modified;
                        db.SaveChanges();
                    }
                }
                //re-Update Tong No
                DVCC old_dvcc = db.DVCCs.Find(idold_dvcc);
                var new_tongno_dvcc = Util.ConvertCurrencyToMoney(old_dvcc.TongNo) - Util.ConvertCurrencyToMoney(oldNK.TongThanhToan) + Util.ConvertCurrencyToMoney(nhapkho.TongThanhToan);
                old_dvcc.TongNo = Util.ConvertDecimaToCurrency(new_tongno_dvcc);
                db.Entry(old_dvcc).State = EntityState.Modified;

                nhapkho.Ma_SP = masp;
                nhapkho.SoLuong = soluong;
                nhapkho.Gia = gia;
                nhapkho.DonVi = donvi;
                this.db.Entry<NhapKho>(oldNK).CurrentValues.SetValues(nhapkho);

                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.ID_DVCC = new SelectList(db.DVCCs, "ID", "TenDVCC", nhapkho.ID_DVCC);
            ViewBag.TenKho = nhapkho.Kho.TenKho;
            ViewBag.CurrentUserDisplayName = currentUser.DisplayName;
            ViewBag.CurrentUserID = currentUser.UserId;
            return View(nhapkho);
        }

        //
        // GET: /NhapKho/Delete/5
        [Authorize(Roles = "Administrator,Staff")]
        public ActionResult Delete(int id = 0)
        {
            NhapKho nhapkho = db.NhapKhoes.Find(id);
            if (nhapkho == null || nhapkho.DVCC.CuaHangID != Convert.ToInt32(Session["CuaHangID"]))
            {
                return HttpNotFound();
            }
            return View(nhapkho);
        }

        //
        // POST: /NhapKho/Delete/5
        [Authorize(Roles = "Administrator,Staff")]
        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            NhapKho nhapkho = db.NhapKhoes.Find(id);
            if (nhapkho == null || nhapkho.DVCC.CuaHangID != Convert.ToInt32(Session["CuaHangID"]))
            {
                return RedirectToAction("Index", "Home");
            }

            // update so luong trong kho            
            var old_Masp = nhapkho.Ma_SP;
            var old_SoLuong = nhapkho.SoLuong;
            var idold_dvcc = nhapkho.ID_DVCC;
            if (!string.IsNullOrEmpty(old_Masp))
            {
                var list_old_Masp = old_Masp.Split(new string[] { ";#" }, StringSplitOptions.None);
                var list_old_SoLuong = old_SoLuong.Split(new string[] { ";#" }, StringSplitOptions.None);
                for (int i = 0; i < list_old_Masp.Length; i++)
                {

                    string sp_old_sp = list_old_Masp[i];
                    if (!string.IsNullOrEmpty(sp_old_sp))
                    {
                        SanPham sp = db.SanPhams.Where(p => p.MaSP == sp_old_sp).FirstOrDefault();
                        SanPhamInKho sanPhamInKho = db.SanPhamInKhoes.Where(s => s.SanPhamID == sp.ID && s.KhoID == nhapkho.KhoID).FirstOrDefault();
                        if (sanPhamInKho != null)
                        {
                            sanPhamInKho.SoLuong -= Convert.ToInt32(list_old_SoLuong[i]);
                            db.Entry(sanPhamInKho).State = EntityState.Modified;
                            db.SaveChanges();
                        }
                    }
                }
            }
            //re-Update Tong No
            DVCC old_dvcc = db.DVCCs.Find(idold_dvcc);
            var new_tongno_dvcc = Util.ConvertCurrencyToMoney(old_dvcc.TongNo) - Util.ConvertCurrencyToMoney(nhapkho.TongThanhToan);
            old_dvcc.TongNo = Util.ConvertDecimaToCurrency(new_tongno_dvcc);
            db.Entry(old_dvcc).State = EntityState.Modified;

            db.NhapKhoes.Remove(nhapkho);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}